package com.acme.service.bank;

import java.util.ArrayList;
import java.util.StringTokenizer;

import com.acme.domain.account.CheckingAccount;
import com.acme.domain.account.SavingAccount;
import com.acme.domain.bank.Client;
import com.acme.domain.bank.Gender;
/**
 * Class which provides methods to parse entities fields
 * and generate entities 
 * 
 * @author render1980
 *
 */
public class BankDataLoaderService {
	
	private int entityId = 0;
	
	public ArrayList<Client> generateClients(String data) {
		if(data == null || data == "") {
			return null;
		}
		ArrayList<Client> clients = new ArrayList<Client>();
		StringTokenizer st = new StringTokenizer(data, "\n", false);
		while(st.hasMoreTokens()) {
			String str = st.nextToken();
			String[] records = str.split(";");
			clients.add(parseClient(records));	
		}
		return clients;
	}
	
	private Client parseClient(String[] records) {
		String name = null;
		char gender = ' ', accountType = ' ';
		double balance = 0, overdraft = 0;
		for(String str: records) {
			String[] vars = str.split("=");
			String key = vars[0];
			String value = vars[1];
			
			if(RecordFields.ACCOUNT_TYPE.getRecordName().equals(key)) {
				accountType = value.charAt(0);
			}
			if(RecordFields.BALANCE.getRecordName().equals(key)) {
				balance = Double.parseDouble(value);
			}
			if(RecordFields.OVERDRAFT.getRecordName().equals(key)) {
				overdraft = Double.parseDouble(value);
			}
			if(RecordFields.NAME.getRecordName().equals(key)) {
				name = value;
			}
			if(RecordFields.GENDER.getRecordName().equals(key)) {
				gender = value.charAt(0);
			}
		}
		
		Client client = new Client(name, Gender.getGender(gender));
		return createClientAccount(client, accountType, balance, overdraft);
	}
	
	private Client createClientAccount(Client client, char accountType, double balance, double overdraft) {
		if(accountType == 's') {
			SavingAccount sAcc = new SavingAccount(entityId, balance);
			client.addAccount(sAcc);
			entityId++;
		} else if(accountType == 'c') {
			CheckingAccount chAcc = new CheckingAccount(entityId, balance, overdraft);
			client.addAccount(chAcc);
			entityId++;
		}
		return client;
	}
}